function varargout = UartDemo(varargin)
% UARTDEMO MATLAB code for UartDemo.fig
%      UARTDEMO, by itself, creates a new UARTDEMO or raises the existing
%      singleton*.
%
%      H = UARTDEMO returns the handle to a new UARTDEMO or the handle to
%      the existing singleton*.
%
%      UARTDEMO('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in UARTDEMO.M with the given input arguments.
%
%      UARTDEMO('Property','Value',...) creates a new UARTDEMO or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before UartDemo_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to UartDemo_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help UartDemo

% Last Modified by GUIDE v2.5 19-Aug-2012 21:28:32

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @UartDemo_OpeningFcn, ...
                   'gui_OutputFcn',  @UartDemo_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before UartDemo is made visible.
function UartDemo_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to UartDemo (see VARARGIN)

% Choose default command line output for UartDemo
handles.output = hObject;

%----------------------------------
% Tung code here
%---------------------------------
%step 1: Scan Serial Ports on computer
global figHandles;
global gFlag ;
gFlag = 0;
SerialInfo = instrhwinfo('serial');  % dang cell nhieu struct
AvaiPorts = SerialInfo.AvailableSerialPorts; % dang cell
if ~isempty(AvaiPorts)
    set(handles.pumnCOM,'string',AvaiPorts);
else
    msgbox('No COM detected');
end

global fid;
global N;
N = 0;
fout = input('Name of save file: ', 's');
fid = fopen(['raw_' fout], 'w+'); 

%----------------------------------
% Update handles structure
guidata(hObject, handles);

% UIWAIT makes UartDemo wait for user response (see UIRESUME)
% uiwait(handles.figure1);
figHandles = handles;

% --- Outputs from this function are returned to the command line.
function varargout = UartDemo_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;



% --- Executes during object creation, after setting all properties.
function ltbxCOM_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ltbxCOM (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

 

% --- Executes during object creation, after setting all properties.
function pumnCOM_CreateFcn(hObject, eventdata, handles)
% hObject    handle to pumnCOM (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes during object creation, after setting all properties.
function pumnBaudRate_CreateFcn(hObject, eventdata, handles)
% hObject    handle to pumnBaudRate (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in butConnect.
function butConnect_Callback(hObject, eventdata, handles)
% hObject    handle to butConnect (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%get property of set up COM
global gFlag;
global sHandles;
if ~gFlag   
    contents = cellstr(get(handles.pumnCOM,'String'));
    comPortName = contents{get(handles.pumnCOM,'value')};
    contents = cellstr(get(handles.pumnBaudRate,'String'));
    comBaudRate = str2double(contents(get(handles.pumnBaudRate,'value')));
    comDataBits = 8;
    comStopBits = 1;
    s = serial(comPortName,'BaudRate',comBaudRate,...
               'DataBits',comDataBits,'StopBits',comStopBits,'InputBufferSize',255, 'BytesAvailableFcnCount',1, 'TimerPeriod', 1);
    %s.BytesAvailableFcnMode = 'Terminator';
    s.BytesAvailableFcnMode = 'byte';
    s.BytesAvailableFcn = @myOnCom_Callback;        %chuong trinh con nhan su kien ngat ON Com
    s.ErrorFcn = @myTimeout_Callback;
    s.TimerFcn = @myTimer_Callback;
    s.Timeout = 100;    % Timeout 100s
    fopen(s);       %mo cong COM
    set(handles.stxtReceive,'string',[comPortName num2str(comBaudRate)]);
    %save context to global variable "sHandles"
    sHandles = s;
    gFlag = 1;
    set(handles.butConnect,'string','Disconnect');
    set(handles.pumnCOM,'Enable','off');
    set(handles.pumnBaudRate,'Enable','off');
else
    gFlag = 0;
    set(handles.butConnect,'string','Connect');
    fclose(sHandles);
    set(handles.pumnCOM,'Enable','on');
    set(handles.pumnBaudRate,'Enable','on');
end
guidata(hObject, handles);    

function myTimeout_Callback(obj,event)
disp('Timeout occur');

function myTimer_Callback(obj,event)
global N;
%disp(N);



%-----Execute on COM serial ports.
function myOnCom_Callback(obj,event)
global sHandles;
global figHandles;
global fid;
%strTemp = get(figHandles.stxtReceive,'string');
%strRecv = fscanf(obj,'%o');
%disp(strRecv);
global state;
global len;
global N;
global FirstByte;
global HeaderField;
global DataField;

if (isempty(state))
    % Init in first time
    state = 0;
end

% bytes = obj.BytesAvailable;
% if (bytes ~= 0)
%     temp = fread(obj, bytes, 'uchar');
%     load matlab
%     Frames = [Frames temp'];
%     N = N + bytes;
%     %fprintf(fid,'%s\r\n' , num2str(temp) );
%     save matlab
% else
%     %disp('0');
% end

bytes = obj.BytesAvailable;
if ( bytes ~= 0)
    if ( (state == 1) && (bytes >= 2) )
        HeaderField = fread(obj, 2, 'uchar'); % |MSG_ID|DataNum|
        len = HeaderField(2) + 1; %Read to '\n'
        state = 2;
    elseif ( (state == 2) && (bytes >= len) )
        DataField = fread(obj, len, 'uchar'); %|Data: len bytes|'\n'|
        frame = [FirstByte; HeaderField; DataField];
        res = FrameProcess(frame);
        % Process result
        FrameRun(res);
        % reset state
        len = 0;
        state = 0;
    else
        state = 0;
        len = 0;
        FirstByte = fread(obj, 1, 'uchar');
        if (FirstByte(1) == 255) % 255
            state = 1;
        end
    end
end





% --- Executes on button press in butSend.
function butSend_Callback(hObject, eventdata, handles)
% hObject    handle to butSend (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global sHandles;
if strcmp(sHandles.Status,'open')
    strSend = get(handles.txtSend,'string');
    fprintf(sHandles,strSend);
else
    msgbox(' plz open COM port');
end
    



function txtSend_Callback(hObject, eventdata, handles)
% hObject    handle to txtSend (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of txtSend as text
%        str2double(get(hObject,'String')) returns contents of txtSend as a double


% --- Executes during object creation, after setting all properties.
function txtSend_CreateFcn(hObject, eventdata, handles)
% hObject    handle to txtSend (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in butClear.
function butClear_Callback(hObject, eventdata, handles)
% hObject    handle to butClear (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.stxtReceive,'string',' ');


% --- Executes when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: delete(hObject) closes the figure
global gFlag;   %kiem tra da tung connect chua
global sHandles;
global fid;
global N;
disp(['Total: ' num2str(N)]);
if gFlag
    if strcmp(sHandles.Status,'open')
        fclose(sHandles);
    end 
end
delete(sHandles);
delete(hObject);
fclose(fid);
